﻿import cityinfo
import config
import time
from time import localtime
from requests import get,post
from email.mime.text import MIMEText
import smtplib
from email.header import Header
# from requests import get, post
from datetime import datetime, date
from email.mime.multipart import MIMEMultipart
 
# 获取城市天气
def get_weather(province, city):
    # 城市id
    city_id = cityinfo.cityInfo[province][city]["AREAID"]
    # city_id = 101280101
    # 毫秒级时间戳
    t = (int(round(time.time() * 1000)))
    headers = {
        "Referer": "http://www.weather.com.cn/weather1d/{}.shtml".format(city_id),
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
    url = "http://d1.weather.com.cn/dingzhi/{}.html?_={}".format(city_id, t)
    response = get(url, headers=headers)
    response.encoding = "utf-8"
    response_data = response.text.split(";")[0].split("=")[-1]
    response_json = eval(response_data)
    print("获取城市天气结果===>",response_json)
    weatherinfo = response_json["weatherinfo"]
    # 天气
    weather = weatherinfo["weather"]
    # 最高气温
    temp = weatherinfo["temp"]
    # 最低气温
    tempn = weatherinfo["tempn"]
    return weather, temp, tempn
 
# 获取今天是第几周，返回字符串
def get_Today_Week():
    y = config.year
    m = config.month
    d = config.day
    startWeek = datetime(y, m, d)
    today = datetime.today()
    d_days = today - startWeek
    trueWeek = (d_days.days // 7) + 1
    print("今天是第几周-===>",str(trueWeek))
    return str(trueWeek)
 
# 获取本周课程
def get_Week_Classes(w):
    if w is not None:
        week_Class = config.classes.get(w)
    else:
        week = get_Today_Week()
        week_Class = config.classes.get(week)
    if week_Class is None:
        return []  # 返回一个空列表或其他默认值
    else:
        return week_Class[:7]# 只返回前7天的课程，以确保不会出现索引越界的问题
 
# 获取今日课程
def get_Today_Class():
    year = localtime().tm_year
    month = localtime().tm_mon
    day = localtime().tm_mday
    today = datetime.date(datetime(year=year, month=month, day=day))
    todayClasses = get_Week_Classes(None)[today.weekday()]
    return todayClasses





# 获取指定星期几的课程
def get_Class(day):
    theClasses = get_Week_Classes(None)[day]
    return theClasses
 
# 计算时间间隔
def calculate_Time_Difference(t1, t2):
    h1 = int(t1[0:2])
    h2 = int(t2[0:2])
    m1 = int(t1[3:5])
    m2 = int(t2[3:5])
    s1 = int(t1[6:8])
    s2 = int(t2[6:8])
    d1 = datetime(2022, 1, 1, h1, m1, s1)
    d2 = datetime(2022, 1, 1, h2, m2, s2)
    return (d1 - d2).seconds
# 计算时间间隔(计算分钟差)
def calculate_Time_Difference2(t1, t2):
    h1 = int(t1[0:2])
    h2 = int(t2[0:2])
    m1 = int(t1[3:5])
    m2 = int(t2[3:5])
    d1 = datetime(2022, 1, 1, h1, m1)
    d2 = datetime(2022, 1, 1, h2, m2)
    diff = (d1 - d2).total_seconds() / 60  # 计算分钟差
    return int(abs(diff))  # 返回绝对值的整数

# 发送每日信息 to_user(用户id)  
def send_message(to_user,city_name, weather, max_temperature, min_temperature):
    week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
    year = localtime().tm_year
    month = localtime().tm_mon
    day = localtime().tm_mday
    today = datetime.date(datetime(year=year, month=month, day=day))
    # 星期几
    week = week_list[today.weekday()]
    # 开学的第几周
    weeks = get_Today_Week()

    #获取今天的课程
    theClass = get_Today_Class()
    theuser = to_user
 
    if all(item == '' for item in theClass):
        #说明今天没课
        subject = "每日提醒(无课版)"
        data =  {
            "weeks": {
                "value": weeks,
                "color": "#00FFFF"
            },
            "date": {
                "value": "{} {}".format(today, week),
                "color": "#00FFFF"
            },
            "city": {
                "value": city_name,
                "color": "#808A87"
            },
            "weather": {
                "value": weather,
                "color": "#ED9121"
            },
            "min_temperature": {
                "value": min_temperature,
                "color": "#00FF00"
            },
            "max_temperature": {
                "value": max_temperature,
                "color": "#FF6100"
            },
        }
        content = config.template2
        html_content = content.format(**data)
        send_email(subject,html_content,theuser)
        print("邮件内容:",html_content)
    else:
        data =  {
            "weeks": {
                "value": weeks,
                "color": "#00FFFF"
            },
            "date": {
                "value": "{} {}".format(today, week),
                "color": "#00FFFF"
            },
            "city": {
                "value": city_name,
                "color": "#808A87"
            },
            "weather": {
                "value": weather,
                "color": "#ED9121"
            },
            "min_temperature": {
                "value": min_temperature,
                "color": "#00FF00"
            },
            "max_temperature": {
                "value": max_temperature,
                "color": "#FF6100"
            },
            # "birthday": {
            #     "value": birth_day,
            #     "color": "#FF8000"
            # },
            "firstClass": {
                "value": theClass[0],
                "color": "#9400D3"
            },
            "secondClass": {
                "value": theClass[1],
                "color": "#9400D3"
            },
            "thirdClass": {
                "value": theClass[2],
                "color": "#9400D3"
            },
            "fourthClass": {
                "value": theClass[3],
                "color": "#9400D3"
            },
            "fifthClass": {
                "value": theClass[4],
                "color": "#9400D3"
            },
        }
        subject = "每日提醒"
        content = config.template1
        html_content = content.format(**data)
        send_email(subject,html_content,theuser)
        print("邮件内容:",html_content)


# 发送课程消息
def send_Class_Message(to_user, classInfo):
    
    theuser = to_user
    data = {
            "classInfo": {
                "value": classInfo,
                "color": "#FF8000"
            }
        }
    subject = "课程单推"
    content = config.template3
    html_content = content.format(**data)
    send_email(subject,html_content,theuser)

    

# 发送晚安心语及第二天课程
def send_Good_Night(to_user):
    week_list = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
    headers = {
        'Content-Type': 'application/json',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
    # 获取天行数据晚安心语
    txUrl = "http://api.tianapi.com/wanan/index"
    key = config.good_Night_Key
    pre_data = {"key": key}
    r = post(txUrl, params=pre_data, headers=headers)
    good_Night = r.json()["newslist"][0]["content"]

    # 获取第二天课表
    year = localtime().tm_year
    month = localtime().tm_mon
    day = localtime().tm_mday
    today = datetime.date(datetime(year=year, month=month, day=day))

    weekClasses = get_Week_Classes(None)
    week = week_list[(today.weekday() + 1) % 7]
    theClass = []
    #如果是礼拜天即最后一天
    if (today.weekday() + 1) % 7 == 0:
        #获取今天是第几周,然后刚好是课程信息中的当前信息,因为是从0开始的
        weekClasses = get_Week_Classes(get_Today_Week())
        theClass = weekClasses[0]
    else:
         #否则获取下一天的课程信息,因为是从0开始的
        theClass = weekClasses[today.weekday() + 1]
    
    theuser = to_user

    if all(item == '' for item in theClass):
        #明天没课
        #获取土味情话
        txUrl = "http://api.tianapi.com/wanan/index"
        key = config.earthy_Love_Words
        pre_data = {"key": key}
        er = post(txUrl, params=pre_data, headers=headers)
        print("er:", er.text)
        earthyLoveWords = er.json()["newslist"][0]["content"]
         #说明明天没课
        print("明天没课")
        print(theClass)
        data = {
            "goodNight": {
                "value": good_Night,
                "color": "#87CEEB"
            },
            "earthyLoveWords": {
                "value": earthyLoveWords,
                "color": "#808A87"
            }
        }
        subject = "晚安心语(无课版)"
        content = config.template5
        html_content = content.format(**data)

        send_email(subject,html_content,theuser)
        print("邮件内容:",html_content)
    else:
        #说明明天有课
        print("明天有课")
        print(theClass)
        data = {
            "goodNight": {
                "value": good_Night,
                "color": "#87CEEB"
                },
            "week": {
                "value": week,
                "color": "#00FFFF"
                },
            "firstClass": {
                "value": theClass[0],
                "color": "#9400D3"
                },
            "secondClass": {
                "value": theClass[1],
                "color": "#9400D3"
                },
            "thirdClass": {
                "value": theClass[2],
                "color": "#9400D3"
                },
            "fourthClass": {
                "value": theClass[3],
                "color": "#9400D3"
                },
            "fifthClass": {
                "value": theClass[4],
                "color": "#9400D3"
                }
        }
        subject = "晚安心语"
        content = config.template4
        html_content = content.format(**data)
        send_email(subject,html_content,theuser)
        print("邮件内容:",html_content)



# 发送邮件
def send_email(subject, content, user):

    smtp_server = config.smtp_server
    username = config.username
    password = config.password
    port = config.port
    # 设置邮件内容
    msg = MIMEMultipart()
    msg['From'] = username
    msg['To'] =  user 
    msg['Subject'] =  subject 
   
     
    # 添加 HTML 内容
    html_content = MIMEText(content, 'html')
    msg.attach(html_content)
    # 发送邮件
    try:
        smtp_obj = smtplib.SMTP(smtp_server,port)
        smtp_obj.starttls()  # 启用安全连接
        smtp_obj.login(username, password)
        smtp_obj.sendmail(username, user, msg.as_string())
        print("邮件发送成功")
    except smtplib.SMTPException as e:
        print("邮件发送失败")
        print("异常!===",e)
 

if __name__ == '__main__':
    # 接收的用户
    user = config.emails
    print('user===>:', user)

    # 传入省份和市获取天气信息
    province, city = config.province, config.city
    weather, max_temperature, min_temperature = get_weather(province, city)
    isPost = False
    
    # 邮箱推送消息
    if datetime.now().strftime('%H:%M:%S') < config.post_Time:
        for i in range(len(user)):
            send_message(user[i],city, weather, max_temperature, min_temperature)
        isPost = True
 

    # 课程提醒推送
    todayClasses = get_Today_Class()
    time_table = config.time_table
    #循环每节课提醒时间（有课才会提醒）
    for i in range(len(time_table)):
        #如果还没到每日推送时间就退出
        if isPost:
            break
        reminderTime =  time_table[i] 
        #否则就循环
        while True:
            # 获取当前时间
            nowTime = datetime.now().strftime('%H:%M:%S')
            reminderTimePlus20 =  calculate_Time_Difference2(reminderTime, nowTime)
            # 判断nowTime是否在reminderTime和reminderTime加上20分钟之间
            print("课程推送时间差:",reminderTimePlus20)

            if reminderTimePlus20<5:
                if len(todayClasses[i]) != 0:
                    classInfo = "课程信息: " + todayClasses[i] + "\n" + "上课时间: " + config.course_Time[i] + "\n"
                    print(classInfo)
                    for i in range(len(user)):
                        send_Class_Message(user[i],classInfo)
                    print("课程信息推送成功！")
                isPost = True
                break
            else:
                break



    #晚安心语推送
    while True:
        goodNightTime = config.good_Night_Time
        nowTime = datetime.now().strftime('%H:%M:%S')
        reminderTimePlus20 =  calculate_Time_Difference2(goodNightTime, nowTime)
        print("晚安心语推送时间差:",reminderTimePlus20)
        if reminderTimePlus20 > 5:
            print("当前时间已过晚安心语推送设置的时间！")
            break
        else:
            for i in range(len(user)):
                send_Good_Night(user[i])
            print("晚安心语推送成功！")
            break


